<script setup>
import { ref, getCurrentInstance } from 'vue';
import { ElMessage } from 'element-plus';
import { useInfoStore } from '@/stores/info';
import {updatePasswordService, updatePhoneService} from "@/api/user.js";
import {useAuthStore} from "@/stores/auth.js";
import {useTokenStore} from "@/stores/token.js";
import {useRouter} from "vue-router";
import {fetchCaptcha} from "@/api/sign.js";

const { $t } = getCurrentInstance().proxy;
const changePwdParams = ref({
  currentPassword:'',
  newPassword:'',
  confirmPassword:''
})
const showPassword = ref(false);
const changePhoneParams = ref({
  currentPhone:'',
  newPhone:'',
  verificationCode:''
})
const countdown = ref(0);
const isSending = ref(false);

const togglePasswordVisibility = () => {
  showPassword.value = !showPassword.value;
}
const validatePassword = (password) => { 
  const regex = /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{8,20}$/
  if(regex.test(password)){
    return true;
  }
  return false;
}

const router = useRouter();
const infoStore = useInfoStore();
const tokenStore = useTokenStore();
const auth = useAuthStore();
const submitPasswordChange = async () => {
  if (!validatePassword(changePwdParams.value.currentPassword)) {
    ElMessage.error($t("error2"));
    return;
  }
  if (!validatePassword(changePwdParams.value.newPassword)) {
    ElMessage.error($t("error2"));
    return;
  }
  if (changePwdParams.value.newPassword !== changePwdParams.value.confirmPassword) {
    ElMessage.error($t("passwordMismatch"));
    return;
  }
  // 提交密码修改api,phone是登陆成功后，后端返回保存的,currentPassword是当前密码,后端还要验证
  // newPassword是修改后的密码,只有验证通过后才能修改成功
  //await submitPasswordChange(store.privateInfo.phone, currentPassword.value, newPassword.value);
  let result = await updatePasswordService(changePwdParams.value)
  ElMessage.success(result.message? result.message:'密码修改成功')
  // 清空输入数据项
  changePwdParams.value.currentPassword = '';
  changePwdParams.value.newPassword = '';
  changePwdParams.value.confirmPassword = '';
  // 退出登录
  infoStore.setInfo('')
  tokenStore.token=''
  auth.setLogin(false)
  //跳转到登录页
  await router.push('/sign')
};
const validatePhone = (phone) => { 
  if (!/^1[3-9]\d{9}$/.test(phone)) {
    ElMessage.error($t("error1"));
    return false;
  }
  return true;
};
const sendVerificationCode = async () => {
  if (!validatePhone(changePhoneParams.value.newPhone)) return;
  if (isSending.value) return;
  isSending.value = true;
  countdown.value = 60;
  ElMessage.success(`${$t("codeSent")}:${changePhoneParams.value.newPhone}`);
  const timer = setInterval(() => {
    countdown.value--;
    if (countdown.value <= 0) {
      clearInterval(timer);
      isSending.value = false;
    }
  }, 1000);
  await fetchCaptcha(changePhoneParams.value.newPhone) // 调用获取验证码API
};
const submitPhoneChange = async () => {
  if(!validatePhone(changePhoneParams.value.currentPhone) || !validatePhone(changePhoneParams.value.newPhone)) return
  if(changePhoneParams.value.currentPhone === changePhoneParams.value.newPhone){
    ElMessage.error($t("phoneMismatch"));
  }
  // 提交修改手机号码api,不仅要判断新手机号是否注册过，还要判断验证码是否正确
  // await changePhone(currentPhone.value, newPhone.value, verificationCode.value)
  let result = await updatePhoneService(changePhoneParams.value)
  ElMessage.success(result.message? result.message:'手机号修改成功')
  changePhoneParams.value.currentPhone = '';
  changePhoneParams.value.newPhone = '';
  changePhoneParams.value.verificationCode = '';
  // 退出登录
  infoStore.setInfo('')
  tokenStore.token=''
  auth.setLogin(false)
  //跳转到登录页
  await router.push('/sign')
};
</script>

<template>
  <div class="settings-content">
    <div class="content-header">
      <h2>{{ $t("setting3") }}</h2>
      <p>{{ $t("accountModificationDesc") }}</p >
    </div>

    <div class="settings-card">
      <h3><i class="fa-solid fa-pen-to-square"></i>{{ $t("passwordChange") }}</h3>
      <div class="settings-item">
        <div class="form-group">
          <label>{{ $t("currentPassword") }}</label>
          <div class="input-with-icon">
            <input
                :type="showPassword ? 'text' : 'password'"  maxlength="20"
                v-model="changePwdParams.currentPassword"
                :placeholder="$t('enterNewPassword')"
            >
            <i
                :class="showPassword ? 'fa-solid fa-eye' : 'fa-solid fa-eye-slash'"
                @click="togglePasswordVisibility"
            ></i>
          </div>
        </div>

        <div class="form-group">
          <label>{{ $t("newPassword") }}</label>
          <input
              :type="showPassword ? 'text' : 'password'" maxlength="20"
              v-model="changePwdParams.newPassword"
              :placeholder="$t('enterNewPassword')"
          >
        </div>

        <div class="form-group">
          <label>{{ $t("confirmPassword") }}</label>
          <input
              :type="showPassword ? 'text' : 'password'"  maxlength="20"
              v-model="changePwdParams.confirmPassword"
              :placeholder="$t('reEnterNewPassword')"
          >
        </div>

        <button class="submit-btn" @click="submitPasswordChange">{{ $t("saveChanges") }}</button>
      </div>
    </div>

    <div class="settings-card">
      <h3><i class="fa-solid fa-pen-to-square"></i> {{ $t("phoneChange") }}</h3>
      <div class="settings-item">
        <div class="form-group">
          <label>{{ $t("currentPhone") }}</label>
          <input
              type="text" maxlength="11"
              v-model="changePhoneParams.currentPhone"
              :placeholder="$t('enterCurrentPhone')"
          >
        </div>

        <div class="form-group">
          <label>{{ $t('newPhone') }}</label>
          <input
              type="text" maxlength="11"
              v-model="changePhoneParams.newPhone"
              :placeholder="$t('enterNewPhone')"
          >
        </div>

        <div class="form-group">
          <label>{{ $t("verificationCode") }}</label>
          <div class="code-input-group">
            <input
                type="text"
                v-model="changePhoneParams.verificationCode"
                :placeholder="$t('enterVerificationCode')"
                maxlength="6"
            >
            <button
                class="code-btn"
                :disabled="isSending"
                @click="sendVerificationCode"
            >
              {{ isSending ? `${countdown}` + $t('resendAfterSeconds') : $t('getCode') }}
            </button>
          </div>
        </div>

        <button class="submit-btn" @click="submitPhoneChange">{{ $t("saveChanges") }}</button>
      </div>
    </div>
  </div>
</template>

<style scoped>
.settings-content {
  background: var(--bgcolor);
  border-radius: 16px;
  box-shadow: 0 6px 25px rgba(0, 0, 0, 0.07);
  padding: 40px;
  min-height: 500px;
  max-width: 1000px;
  margin-left: calc(50vw - 500px);
  color: var(--txcolor);
  border: 1px solid var(--border-color);
}

.content-header {
  margin-bottom: 30px;
}

.content-header h2 {
  font-size: 1.8rem;
  color: var(--header-color);
  margin-bottom: 10px;
}

.content-header p {
  color: var(--secondary-text);
  font-size: 1rem;
  max-width: 600px;
  line-height: 1.6;
}

.settings-card {
  background: var(--card-bg);
  border-radius: 12px;
  padding: 25px;
  margin-bottom: 25px;
  border: 1px solid var(--border-color);
}

.settings-card h3 {
  font-size: 1.2rem;
  color: var(--header-color);
  margin-bottom: 20px;
  display: flex;
  align-items: center;
  gap: 10px;
}

.settings-card h3 i {
  color: var(--accent-color);
}

.settings-item {
  padding: 15px 0;
}

.form-group {
  margin-bottom: 20px;
}

.form-group label {
  display: block;
  margin-bottom: 8px;
  font-weight: 500;
  color: var(--h4-color);
}

.form-group input {
  width: 100%;
  padding: 12px 15px;
  border: 1px solid #cbd5e1;
  border-radius: 8px;
  font-size: 1rem;
  transition: border-color 0.3s;
  background-color: var(--select-color);
  color: var(--txcolor);
}

.form-group input:focus {
  border-color: #3b82f6;
  outline: none;
  box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.15);
}

.form-group input:disabled {
  background-color: #f1f5f9;
  cursor: not-allowed;
}

.input-with-icon {
  position: relative;
}

.input-with-icon i {
  position: absolute;
  right: 15px;
  top: 50%;
  transform: translateY(-50%);
  color: #94a3b8;
  cursor: pointer;
  transition: color 0.3s;
}

.input-with-icon i:hover {
  color: #3b82f6;
}

.code-input-group {
  display: flex;
  gap: 10px;
}

.code-input-group input {
  flex: 1;
}

.code-btn {
  padding: 0 15px;
  background: #e2e8f0;
  border: none;
  border-radius: 8px;
  color: #334155;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s;
  white-space: nowrap;
}

.code-btn:hover:not(:disabled) {
  background: #cbd5e1;
}

.code-btn:disabled {
  opacity: 0.7;
  cursor: not-allowed;
}

.submit-btn {
  width: 100%;
  padding: 12px;
  background: #3b82f6;
  color: white;
  border: none;
  border-radius: 8px;
  font-size: 1rem;
  font-weight: 500;
  cursor: pointer;
  transition: background 0.3s;
  margin-top: 10px;
}

.submit-btn:hover {
  background: #2563eb;
}
</style>